/*
 * Copyright (c) 2024 Huawei Technologies Co., Ltd.
 * openUBMC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *         http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

#include "interface/network_port/lldp_receive.h"
#include <mc/log.h>

namespace dev {

bool NetworkPort_LLDPReceive::enable_lldp_capability_by_ncsi(uint8_t port_id) {
    bool ret = m_ncsi_over_mctp_wx->enable_lldp(DEFAULT_PACKAGE_ID, port_id);
    if (!ret) {
        elog("Error: Failed to enable LLDP capability");
        return false;
    }
    return true;
}

bool NetworkPort_LLDPReceive::disable_lldp_capability_by_ncsi(uint8_t port_id) {
    bool ret = m_ncsi_over_mctp_wx->disable_lldp(DEFAULT_PACKAGE_ID, port_id);
    if (!ret) {
        elog("Error: Failed to disable LLDP capability");
        return false;
    }
    return true;
}

bool NetworkPort_LLDPReceive::get_lldp_capability_by_ncsi(uint8_t port_id) {
    uint8_t lldp_capability = 0;
    bool    lldp_enable     = LLDPEnabled.get_value().as<bool>();
    if (lldp_enable) {
        return true;
    }
    bool ret =
        m_ncsi_over_mctp_wx->get_lldp_capability(DEFAULT_PACKAGE_ID, port_id, &lldp_capability);
    if (!ret) {
        elog("Error: Failed to get LLDP capability");
        return false;
    }
    // 未使能时，使能LLDP，使能失败设置为flase
    if (lldp_capability == 0) {
        if (!enable_lldp_capability_by_ncsi(port_id)) {
            LLDPEnabled.set_value(false);
            return false;
        }
    }
    // 已使能或使能成功时，设置为true
    LLDPEnabled.set_value(true);
    return true;
}

void NetworkPort_LLDPReceive::start_ncsi_update_task_wx(ncsi_over_mctp_wx_ptr ncsi_over_mctp,
                                                        mc::milliseconds      interval,
                                                        uint8_t               port_id) {
    m_ncsi_over_mctp_wx = ncsi_over_mctp;
    m_ncsi_timer        = new mc::core::timer(this);
    m_ncsi_timer->timeout.connect([this, port_id]() {
        get_lldp_capability_by_ncsi(port_id);
    });
    m_ncsi_timer->set_single_shot(false);
    m_ncsi_timer->start(interval);
}

void NetworkPort_LLDPReceive::stop_ncsi_update_task() {
    m_ncsi_timer->stop();
}
} // namespace dev

MC_REFLECT(dev::NetworkPort_LLDPReceive)